<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="setting_box box-card">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <!--            按钮-->
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="editDialogVisible=true">新增角色</el-button>
            <!--表格-->
            <el-table
              border
              :data="tableData"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                label="序号"
                width="130"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="180"
                sortable
              />

              <el-table-column
                prop="description"
                label="描述"
                sortable
              />
              <el-table-column
                align="center"
                prop="address"
                width="251"
                label="操作"
              >
                <template v-slot="scope">
                  <el-button type="text" size="mini" @click="onClickSetPermission(scope.row)">分配权限</el-button>
                  <el-button type="text" size="mini" @click="handleEdit(scope.row)">修改</el-button>
                  <el-button type="text" size="mini" @click="delRole(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page.page"
              :page-size="page.pagesize"
              layout="total, prev, pager, next"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="info">
            <!--            公司信息-->
            <CompanyInfo />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!--    编辑对话框-->
    <el-dialog
      :title="(form.id?'编辑':'新增')+'角色'"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="setPermissionTitle"
      :visible.sync="setPermissionDialog"
      width="50%"
    >
      <el-tree
        ref="setPermission"
        :check-strictly="true"
        :data="setPermissionData"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        icon-class=" "
        node-key="id"
        :default-checked-keys="defaultKeys"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="setPermissionDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSaveSetPermission">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addRole, delRoleById, getRoleById, getRolesList, updateRoleById } from '@/api/company'
import CompanyInfo from '@/views/setting/components/CompanyInfo'
import { getAllPermission, setPermission } from '@/api/permission'
import { handleLoading, transListToTree } from '@/utils'

export default {
  name: 'Settings',
  components: {
    CompanyInfo
  },
  data() {
    return {
      activeName: 'role',
      tableData: [],
      total: 20,
      page: {
        page: 1,
        pagesize: 10
      },
      editDialogVisible: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      setPermissionDialog: false, // 分配权限对话框
      setPermissionTitle: '', // 分配权限对话框标题
      setPermissionData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultKeys: [],
      currentId: ''// 选中某一个分配权限的id
    }
  },
  created() {
    this.loadRolesList() // 加载列表
  },

  methods: {
    // 弹窗点击确定之后
    async onSubmit() {
      try {
        await this.$refs.form.validate() // 校验表单
        if (this.form.id) {
          // 编辑
          await updateRoleById(this.form)
          this.$message.success('编辑成功')
        } else {
          // 添加
          await addRole(this.form)
          this.$message.success('添加成功')
        }
        await this.loadRolesList()
        this.editDialogVisible = false
      } catch (e) {
        console.log(e)
      }
    },
    async loadRolesList() {
      const { total, rows } = await getRolesList(this.page)
      this.tableData = rows
      this.total = total
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.loadRolesList()
    },
    // 删除角色
    async delRole(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRoleById(row.id)
        await this.loadRolesList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
      })
    },
    async handleEdit(row) {
      this.form = await getRoleById(row.id)
      this.editDialogVisible = true
    },
    // 监听弹窗关闭
    handleClose() {
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 分配权限
    async onClickSetPermission(row) {
      this.setPermissionDialog = true
      this.$nextTick(() => {
        handleLoading(async() => {
          this.setPermissionData = transListToTree(await getAllPermission(), '0')
          this.setPermissionTitle = `为[${row.name}]分配权限`
          const { permIds } = await getRoleById(row.id)
          this.defaultKeys = permIds
          this.currentId = row.id
        }, '.el-dialog__body')
      })
    },
    // 分配权限对话框点击确定时
    async onSaveSetPermission() {
      const permissionIds = this.$refs.setPermission.getCheckedKeys()
      if (!permissionIds) return this.$message.warning('请选择必要的权限')
      if (this.defaultKeys.sort().toString() === permissionIds.sort().toString()) return this.$message.warning('没有发现修改权限')
      await setPermission({ id: this.currentId, permIds: permissionIds })
      this.$message.success('分配权限成功')
      this.setPermissionDialog = false
    }
  }
}
</script>

<style scoped lang='scss'>
.setting_box {
  ::v-deep .el-tabs__item {
    font-size: 18px;
    text-align: center;
    width: 150px;
  }

  .el-pagination {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
